package com.authine.cloudpivot.ext.controller.auth;

import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.ext.Utils.AccountAuthorize;
import com.authine.cloudpivot.ext.Utils.DocAPI;
import com.authine.cloudpivot.ext.Utils.RoleAuth;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.ext.service.RoleAuthService;
import com.authine.cloudpivot.web.api.controller.runtime.WorkflowInstanceRuntimeController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RequestMapping("/public/FileAuth")
@RestController
@Slf4j
public class FileAuth  extends WorkflowInstanceRuntimeController {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private CloudSqlService sqlService;

    @Autowired
    private RoleAuthService roleAuthService;


    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    @Async
    @GetMapping("BaseCorpArchiveAuth")
    //总公司基层授权
    public ResponseResult BaseCorpArchiveAuth(@RequestParam String bizId) {

        // TODO Auto-generated method stub

        DocAPI api=new DocAPI();
        RoleAuth RoleAuth=new RoleAuth();
        String token =api.getToken();
        String code ="";
        String MainDeptCode = "";
        String MainDeptName = "";
        JSONObject FileID=null;
        String temp="";
        String manageDept = "";
        String manageDeptSimpleName = "";
        Map<String, Object> objectMap = null;
        String PosCode="";
        String authCode="";


        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("PrimaryLevelAuthInfo", bizId);

        List<Map<String, Object>> subSheet = (List<Map<String, Object>>) bizObject.getObject("PrimaryLevelAuthInfoSheet1");


        int n=subSheet.size();

        objectMap = subSheet.get(0);
        //获取表单上主责部门
        MainDeptCode = (String) objectMap.get("manaDeptNumber");
        MainDeptName = (String) objectMap.get("manaDeptName");

        for(int i=0;i<n;i++)
        {
            //获取档案代码
            objectMap = subSheet.get(i);
            String ArchCode=(String) objectMap.get("archCodeYingshe");

            // 获取基层组织代码
            String OrgCode=(String) objectMap.get("baseOrgNumber");

            // 获取档案类型号
            String ArchType=(String) objectMap.get("archTypeNumber");

            //如果是监控，则对监控后台授权
            if (ArchType.equalsIgnoreCase("23")) {
                String sql="";
                List<Map<String, Object>> rs =null;
                //获取监控后台token
                AccountAuthorize obj = new AccountAuthorize();
                String FirstAuthorize=  obj.testFirstAuthorize("system","192.168.11.43:5443","WINPC_V1");
                JSONObject FirstAuthorizeObj = JSONObject.fromObject(FirstAuthorize);
                String realm=FirstAuthorizeObj.getString("realm");
                String randomKey=FirstAuthorizeObj.getString("randomKey");
                String encryptType=FirstAuthorizeObj.getString("encryptType");
                String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlrrLOJnJE6MfIk82R2EbmBHv9cq6RaWKehuN5y8WiRfxDhwG2wE4ZFjjs831GcrZz8SZKcW/OcWlTs88JqleSbyDSAw+hxLSyCN9cKVO0rP7APYjS5XAus/77ftA4EO+2SKm+AKksx+ajm4vH2MfbXJOE2c9Ypd9nKYhONVH/pxauCtQmntt4gwX0+TnrAhPcQ2cUHkcLdAWYDFUUsabJFQr4JMuZ0C9L2N/lhj9koc2OLYNdiXUfxb0dXLrMhnO4Dbi/slW1PgQAolMXm4o161zFHI3KptlqkBrKfUiaZqcAyYOi3cNV8BrhtM2zRJ5qbyUhn0zmEzmkZZJvk+b4wIDAQAB";
                String password="ht123456";
                String username="system";
                String Vediotoken=" ";
                temp = md5(password);
                temp = md5(username + temp);
                temp = md5(temp);
                temp = md5(username + ":" + realm + ":" + temp);
                String  signature = md5(temp + ":" + randomKey);
                int aa=0;
                String VedioRoleAuthList="A";
                String PosFid="";
                String PosName="";
                String PosDuty="";
                String RolePosAName="";
                String RolePosId="";
                String FauthId="";
                String SecondAuthorize=  obj.testSecondAuthorize(  "C8:D9:D2:16:AF:F6", signature, username, randomKey, publicKey, encryptType, "192.168.11.43", "WINPC_V1" , "0" ) ;
                JSONObject SecondAuthorizeObj = JSONObject.fromObject(SecondAuthorize);
                Vediotoken=SecondAuthorizeObj.getString("token");


                for (int j = 1; j <= 10; j++) {
                    authCode ="auth".concat(StringUtils.leftPad(String.valueOf(j), 3, "0"));//auth001
                    FauthId=(String) objectMap.get(authCode);
                    if(!StringUtils.isEmpty(FauthId))
                    {
                        //给授权需求部门助理AuthReqDeptAssDuty、上级直至董事长授权
                        VedioRoleAuthList="";
                        //001-010岗授权
                        PosCode = OrgCode.concat(".").concat(StringUtils.leftPad(String.valueOf(j),3,"0"));
                        sql = "select fid,  fname_l2 ,FNUMBER from  [HG_LINK].[hg].dbo.T_ORG_Position where  fnumber='"+ PosCode+ "'";
                        rs = sqlService.getList(CloudSqlService.htEas, sql);
                        try {
                            for(Map<String,Object> m : rs){
                                PosFid = (String)m.get("fid");
                                PosName = (String)m.get("fname_l2");
                                PosDuty=(String)m.get("FNUMBER");
                                if(PosFid!=null&&!PosName.equalsIgnoreCase("董事长")){
                                    //找岗位上级直至董事长
                                    sql = "select B.fname_l2 as fname_l2,B.FNUMBER as FNUMBER ,B.FID from  [HG_LINK].[hg].dbo.T_ORG_PositionHierarchy A inner join [HG_LINK].[hg].dbo.T_ORG_POSITION B ON A.FPARENTID=B.FID where  A.fchildid='"+ PosFid + "'";
                                    rs = sqlService.getList(CloudSqlService.htEas, sql);
                                    //查询该岗位下的所有监控权限
                                    VedioRoleAuthList="";
//									String sqlRoleAuthList01="select   FP_1 ,fnumber from  T_FIL_DeptFileBae   where  FNumber  like  'MT%' and  FOrgDeptID=(select  fid  from   T_ORG_Admin where  FNumber='02.12'   )";
                                    String sqlRoleAuthList01="select * from (select  CASE  RIGHT('"+ PosDuty + "',3)  WHEN  '001' THEN    FP_1    WHEN  '002'  THEN  FP_2  WHEN  '003'  THEN  FP_3 WHEN  '004'  THEN  FP_4 WHEN  '005'  THEN  FP_5 WHEN  '006'  THEN  FP_6 WHEN  '007'  THEN  FP_7 WHEN  '008'  THEN  FP_8 WHEN  '009'  THEN  FP_9 WHEN  '010'  THEN  FP_10 END as auth , FNumber from  [HG_LINK].[hg].dbo.T_FIL_DeptFileBae    where  FNumber  like  'MT%'  and  FOrgDeptID=(select  FAdminOrgUnitID  from   [HG_LINK].[hg].dbo.T_ORG_Position  where  FNumber='"+ PosDuty + "'   )	) t1 where auth in ('99','8','9') 	";
                                    List<Map<String, Object>> rsRoleAuthList01 = sqlService.getList(CloudSqlService.htEas, sqlRoleAuthList01);
                                    try {
                                        for(Map<String,Object> mm : rsRoleAuthList01){
                                            String fnumber =  (String)mm.get("fnumber");
                                            if(fnumber!=null){
                                                VedioRoleAuthList=VedioRoleAuthList+","+fnumber;
                                            }
                                        }
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                    VedioRoleAuthList=VedioRoleAuthList+' ';
                                    VedioRoleAuthList=VedioRoleAuthList.substring(1, VedioRoleAuthList.length());
                                    obj.UpdateRole( Vediotoken, PosDuty,  "实时预览" , "","test" ) ;
                                    obj.UpdateRole( Vediotoken, PosDuty,  "实时预览" , "","test " ) ;
                                    obj.UpdateRole( Vediotoken, PosDuty,  "实时预览" , "",VedioRoleAuthList ) ;
                                    obj.UpdateRole( Vediotoken, PosDuty,  "实时预览" , "",VedioRoleAuthList+" " ) ;

                                    //查询该岗位+C下的所有监控权限
                                    VedioRoleAuthList="";
                                    String sqlRoleAuthList02="select * from (select  CASE  RIGHT('"+ PosDuty + "',3)  WHEN  '001' THEN    FP_1    WHEN  '002'  THEN  FP_2  WHEN  '003'  THEN  FP_3 WHEN  '004'  THEN  FP_4 WHEN  '005'  THEN  FP_5 WHEN  '006'  THEN  FP_6 WHEN  '007'  THEN  FP_7 WHEN  '008'  THEN  FP_8 WHEN  '009'  THEN  FP_9 WHEN  '010'  THEN  FP_10 END as auth , FNumber from  [HG_LINK].[hg].dbo.T_FIL_DeptFileBae    where  FNumber  like  'MT%'  and  FOrgDeptID=(select  FAdminOrgUnitID  from   [HG_LINK].[hg].dbo.T_ORG_Position  where  FNumber='"+ PosDuty + "'   )	) t1 where auth in ('99','9','1','5') 	";
                                    List<Map<String, Object>> rsRoleAuthList02 = sqlService.getList(CloudSqlService.htEas, sqlRoleAuthList02);
                                    try {
                                        for(Map<String,Object> mmm : rsRoleAuthList02){
                                            String fnumber =  (String)mmm.get("fnumber");
                                            if(fnumber!=null){
                                                VedioRoleAuthList=VedioRoleAuthList+","+fnumber;
                                            }
                                        }
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }


                                    VedioRoleAuthList=VedioRoleAuthList+' ';
                                    VedioRoleAuthList=VedioRoleAuthList.substring(1, VedioRoleAuthList.length());
                                    String PosDutyC=PosDuty+'C';
                                    obj.UpdateRole( Vediotoken, PosDutyC,  "实时预览,录像回放" , "录像查看,","test " ) ;
                                    obj.UpdateRole( Vediotoken, PosDutyC,  "实时预览,录像回放" , "录像查看,","test" ) ;
                                    obj.UpdateRole( Vediotoken, PosDutyC,  "实时预览,录像回放" , "录像查看,",VedioRoleAuthList ) ;
                                    obj.UpdateRole( Vediotoken, PosDutyC,  "实时预览,录像回放" , "录像查看,",VedioRoleAuthList+" " ) ;

                                }
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }


                    }

                }

             }

            System.out.println(ArchCode);
            String elec=(String) subSheet.get(0).get("elec");
            if(elec.equalsIgnoreCase("√"))
            {
                //根据扩展属性（档案代码）查询文件id
                String attribute=ArchCode;
                FileID=api.getFileID(attribute);
                System.out.println(FileID);
                code = FileID.getString("code");
                if(FileID.getString("num").equals("0")&&ArchType.equalsIgnoreCase("23")){
                    continue;

                }
                if(FileID.getString("num").equals("0")){
                    attribute = attribute+" "+MainDeptCode;
                    FileID=api.getFileID(attribute);
                }

                JSONArray filearray = FileID.getJSONArray("data");
                JSONObject filearray1 = filearray.getJSONObject(0);
                String fileId = filearray1.getString("id");



                //拼凑角色名称（02.01.001  综管部领导）
                for (int j = 1; j <= 10; j++) {
                    PosCode = OrgCode.concat(".").concat(StringUtils.leftPad(String.valueOf(j),3,"0"));
                    String  abc="select  fname_l2  from  [HG_LINK].[hg].dbo.T_ORG_Position where  fnumber='"+PosCode+"'";
                    List<Map<String, Object>> rs = sqlService.getList(CloudSqlService.htEas, abc);
                    try {
                        String posname=(String)rs.get(0).get("fname_l2");
                        if(posname!=null){
                            String role=PosCode+" "+posname;
                            String roleName=role;
                            //授予角色对应权限
                            JSONObject array1=api.getRole( roleName);
                            String num=array1.getString("num");
                            if(!num.equals("0")){
                                JSONArray array = array1.getJSONArray("data");
                                JSONObject array2 = array.getJSONObject(0);
                                String userId = array2.getString("id");

                                authCode ="auth".concat(StringUtils.leftPad(String.valueOf(j), 3, "0"));//auth001
                                String FauthId=(String) objectMap.get(authCode);
                                if(FauthId.equalsIgnoreCase("√"))
                                {String auth="VP";
                                    JSONObject auth1=api.getRoleAuth( roleName, userId, auth, fileId);
                                    System.out.println(auth1) ;}
                                else if(FauthId.equalsIgnoreCase("▲")){String auth="VPD";
                                    JSONObject auth1=api.getRoleAuth( roleName, userId, auth, fileId);
                                    System.out.println(auth1) ;}

                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }




//			   }
            }

        }

        //dfec.get(1);

        return getOkResponseResult("成功");
    }



    @Async
    @GetMapping("ComBaseArchiveAuth")
    //公司基层授权
    public ResponseResult ComBaseArchiveAuth(@RequestParam String bizId) {
        // TODO Auto-generated method stub

        DocAPI api=new DocAPI();
        RoleAuth RoleAuth=new RoleAuth();
        String token =api.getToken();
        String elec="";
        String F001authId="";
        String F002authId="";
        String F003authId="";
        String F004authId="";
        String F005authId="";
        String F006authId="";
        String F007authId="";
        String F008authId="";
        String F009authId="";
        String F010authId="";
        String fileId="";
        String archType="";
        String PosADuty = "";
        String MainDeptCode = "";
        String MainDeptName = "";
        Map<String, Object> objectMap = null;
        String PosCode="";
        String authCode="";
        String FolderAttribute="";
        String basicCode="";


        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("comPrimaryLevelAuthInfo", bizId);

        List<Map<String, Object>> subSheet = (List<Map<String, Object>>) bizObject.getObject("comPrimaryLevelAuthInfoSheet");

        objectMap = subSheet.get(0);
            // 获取岗位A角色、主责岗位角色、岗位B角色
            PosADuty=(String) objectMap.get("postionACode");
            //获取表单上主责部门
            MainDeptCode = (String) objectMap.get("mainDepartmentNumber");
            MainDeptName = (String) objectMap.get("mainDepartmentName");
            int n=subSheet.size();
            for(int i=0;i<n;i++)
            {
                objectMap = subSheet.get(i);
                String ArchCode=(String) objectMap.get("archCodeYingshe");
                // 获取档案类型号
                archType=(String) objectMap.get("archTypeNumber");
                elec=(String) subSheet.get(0).get("elec");
                if(elec.equalsIgnoreCase("×")||elec.equalsIgnoreCase("/"))
                {
                    continue;
                }
                //获取档案代码、基础代码
                ArchCode=(String) objectMap.get("fileCode");
                basicCode=(String) objectMap.get("basicCode");
                //先找文件
                JSONObject FileID=api.getFileID(ArchCode);
                int FileExist=Integer.parseInt(FileID.getString("num"));

                //找不到文件的情况默认为带分项的文件，找到其对应文件夹
                if (archType.equalsIgnoreCase("15")) {
                    FolderAttribute = ArchCode+ " "+ MainDeptCode;
                }
                if (archType.equalsIgnoreCase("13")) {
                    FolderAttribute = ArchCode+ " "+ PosADuty;
                }
                if (archType.equalsIgnoreCase("12")) {
                    FolderAttribute =ArchCode+ " "+ PosADuty;
                }
                if (archType.equalsIgnoreCase("14")) {
                    FolderAttribute = ArchCode+ " "+ basicCode;
                }
                JSONObject FolderIDObj=api.getFileID(FolderAttribute);
                int FolderIDNum=Integer.parseInt(FolderIDObj.getString("num"));
                if(FolderIDNum==0)
                {
                    continue;
                }
                if(FolderIDNum>0)
                {
                    JSONArray FolderIDDataArray = FolderIDObj.getJSONArray("data");
                    JSONObject FolderIDDataObj = FolderIDDataArray.getJSONObject(0);
                    fileId = FolderIDDataObj.getString("id");
                }
                JSONObject FolderListObj=api.getList( fileId);
                JSONArray FolderListDataArray = FolderListObj.getJSONArray("data");//对应文件夹里的文件List
                int FolderListNum = FolderListDataArray.size();
                int s=0;
                for(int FileNum = 0; FileNum < FolderListDataArray.size(); FileNum++)
                {
                    JSONObject FolderListDataObj = FolderListDataArray.getJSONObject(FileNum);
                    String IsFolder=FolderListDataObj.getString("fileType");
                    if(!IsFolder.equals("1")){
                        s++;
                    }

                }


                if(s<=1&&FileExist>0)
                {
                    JSONArray filearray = FileID.getJSONArray("data");
                    JSONObject filearray1 = filearray.getJSONObject(0);
                    fileId = filearray1.getString("id");

                }

                //拼凑角色名称（02.01.001  综管部领导）

                String OrgCode=(String) objectMap.get("baseOrgNumber");//基层组织代码


                //拼凑角色名称（02.01.001  综管部领导）
                for (int j = 1; j <= 10; j++) {
                    PosCode = OrgCode.concat(".").concat(StringUtils.leftPad(String.valueOf(j),3,"0"));
                    String  abc="select  fname_l2  from  [HG_LINK].[hg].dbo.T_ORG_Position where  fnumber='"+PosCode+"'";
                    List<Map<String, Object>> rs = sqlService.getList(CloudSqlService.htEas, abc);
                    try {
                        String posname=(String)rs.get(0).get("fname_l2");
                        if(posname!=null){
                            String role=PosCode+" "+posname;
                            String roleName=role;
                            //授予角色对应权限
                            JSONObject array1=api.getRole( roleName);
                            String num=array1.getString("num");
                            if(!num.equals("0")){
                                JSONArray array = array1.getJSONArray("data");
                                JSONObject array2 = array.getJSONObject(0);
                                String userId = array2.getString("id");

                                authCode ="auth".concat(StringUtils.leftPad(String.valueOf(j), 3, "0"));//auth001
                                String FauthId=(String) objectMap.get(authCode);
                                if(FauthId.equalsIgnoreCase("√"))
                                {String auth="VP";
                                    JSONObject auth1=api.getRoleAuth( roleName, userId, auth, fileId);
                                    System.out.println(auth1) ;}
                                else if(FauthId.equalsIgnoreCase("▲")){String auth="VPD";
                                    JSONObject auth1=api.getRoleAuth( roleName, userId, auth, fileId);
                                    System.out.println(auth1) ;}

                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }



        return getOkResponseResult("成功");
    }


}
